<script>
import EditUserInfo from "./components/editUserInfo.vue";
import loginInfo from "./util/loginInfo";
import multiavatar from '@multiavatar/multiavatar/esm'
export default {
    components: {
        EditUserInfo
    },
    data() {
        let checkPwd = (rule, value, callback) => {
            if (value.length < 8 || value.length > 16) {
                callback(new Error('密码长度为8~16个字符'))
            }
            if (/^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{8,16}$/.test(value)) {
                callback();
            } else {
                callback(new Error('密码需要由大小写字母加数字组成（不包含特殊字符）'))
            }
        }
        let checkNewPwdAgain = (rule, value, callback) => {
            if (value === this.formModifyPassword.newPwd) {
                callback();
            } else {
                callback(new Error('两次输入的密码不一致'))
            }
        }
        let checkNewPwd = (rule, value, callback) => {
            if (value !== this.formModifyPassword.pwd) {
                callback();
            } else {
                callback(new Error('新密码与旧密码不能相同'))
            }
        }
        return {
            activeTabName: 'first',
            userInfo: {
                id: 0,
                username: '',
                gender: 0
            },
            formUserInfo: {
                // "userId": 123,
                // "userEmail": "abc@email.com",
                // "userStuId": "202108010500",
                // "userName": "张三",
                // "userGender": 1,
                // "userAge": 16,
                // "userBio": "",
                // "userGroup": 1
            },
            formModifyPassword: {
                pwd: '',
                newPwd: '',
                newPwdAgain: ''
            },
            formModifyPasswordRules: {
                pwd: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { validator: checkPwd, trigger: 'blur' }],
                newPwd: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { validator: checkPwd, trigger: 'blur' },
                    { validator: checkNewPwd, trigger: 'blur' }],
                newPwdAgain: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { validator: checkPwd, trigger: 'blur' },
                    { validator: checkNewPwdAgain, trigger: 'blur' }]
            },
        }
    },
    async mounted() {
        await loginInfo.update()
        if (loginInfo.isLogin()) {
            this.userInfo.username = loginInfo.user.userName
            this.userInfo.gender = loginInfo.user.userGender
            this.userInfo.id = loginInfo.user.userId

            this.formUserInfo = {
                userEmail: loginInfo.user.userEmail,
                userStuId: +loginInfo.user.userStuId,
                userName: loginInfo.user.userName,
                userGender: loginInfo.user.userGender,
                userAge: loginInfo.user.userAge,
                userBio: loginInfo.user.userBio
            }
        } else {
            location.href = '/login.html'
        }
    },
    methods: {
        multiavatar,
        onRemoveSelf() {
            this.$confirm('注销账号后无法恢复，确定要注销吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(`/users/${loginInfo.user.userId}`, {
                    headers: {
                        'token': loginInfo.getToken()
                    }
                }).then((v) => {
                    if (v.status === 200) {
                        this.$message.success('注销成功!');
                        loginInfo.logout()
                        location.href = '/index.html'
                    } else {
                        this.$message.warning(v.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onModifyPwd(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 验证通过
                    this.$http.put(`/users/${loginInfo.user.userId}/password`, {
                        "userPwd": this.formModifyPassword.pwd,
                        "userStdId": this.formModifyPassword.newPwd
                    }, {
                        headers: {
                            'token': loginInfo.getToken()
                        }
                    }).then((v) => {
                        if (v.status == 200) {
                            this.$message.success('修改密码成功！请重新登录')
                            setTimeout(() => {
                                loginInfo.logout()
                                location.href = '/login.html'
                            }, 500)
                        } else {
                            this.$message.error(v.msg)
                        }
                    })
                } else {
                    // 验证失败
                    return false;
                }
            });
        },
        onSaveUserInfo() {
            // 验证通过
            console.log(this.formUserInfo)
            this.$http.put(`/users/${loginInfo.user.userId}`, {
                "userEmail": this.formUserInfo.userEmail,
                "userStuId": this.formUserInfo.userStuId + '',
                "userName": this.formUserInfo.userName,
                "userGender": this.formUserInfo.userGender,
                "userAge": this.formUserInfo.userAge,
                "userBio": this.formUserInfo.userBio
            }, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status == 200) {
                    this.$message.success('保存成功！')
                    setTimeout(() => {
                        location.reload()
                    }, 500)
                } else {
                    this.$message.error(v.msg)
                }
            })
        },
        onLogout() {
            loginInfo.logout()
            location.href = '/login.html'
        },
    }
}

</script>

<template>
    <el-card shadow="never">
        <el-row>
            <el-col style="display: flex; align-items: center;">
                <div style="width: 100px;" v-html="multiavatar(userInfo.id)"></div>

                <h2 style="margin: 0 20px;">{{ userInfo.username }}</h2>
                <el-icon v-if="userInfo.gender === 1" :size="25" color="#409eff">
                    <male />
                </el-icon>
                <el-icon v-else-if="userInfo.gender === 2" :size="25" color="#f09ad3">
                    <female />
                </el-icon>
                <el-button @click="onLogout" plain type="danger" style="margin-left: 50px;">退出登录</el-button>
            </el-col>
        </el-row>

        <el-row style="margin-top: 30px; padding: 0 30px;min-height: 300px;">
            <el-col :span="24">
                <el-tabs v-model="activeTabName">
                    <el-tab-pane label="修改个人信息" name="first">
                        <h3>修改个人信息</h3>
                        <EditUserInfo
                            style="width: 35%;"
                            @submit="onSaveUserInfo()"
                            :data="formUserInfo"
                        ></EditUserInfo>
                    </el-tab-pane>
                    <el-tab-pane label="修改密码" name="second">
                        <h3>修改密码</h3>
                        <el-form
                            style="width: 35%;"
                            ref="formModifyPassword"
                            :rules="formModifyPasswordRules"
                            label-position="right"
                            label-width="150px"
                            :model="formModifyPassword"
                        >
                            <el-form-item label="旧密码：" prop="pwd">
                                <el-input
                                    type="password"
                                    prefix-icon="Lock"
                                    placeholder="请输入当前密码"
                                    v-model="formModifyPassword.pwd"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="新密码：" prop="newPwd">
                                <el-input
                                    type="password"
                                    prefix-icon="Lock"
                                    placeholder="请输入新密码"
                                    v-model="formModifyPassword.newPwd"
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="再次输入新密码：" prop="newPwdAgain">
                                <el-input
                                    type="password"
                                    prefix-icon="Lock"
                                    placeholder="请再次输入新密码"
                                    v-model="formModifyPassword.newPwdAgain"
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button
                                    @click="onModifyPwd('formModifyPassword')"
                                    type="primary"
                                >确认修改</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="账户安全设置" name="third">
                        <h3>账户安全设置</h3>
                        <el-button @click="onRemoveSelf" type="danger" style="margin-left: 30px;">注销</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>
    </el-card>
</template>

<style>
</style>